package system

import (
	"context"

	"portal/internal/common"
	"portal/internal/errorx"
	"portal/internal/svc"
	"portal/internal/tool/auth"
	"portal/internal/types"
	"portal/model"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

type DeleteMenuLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	menuModel model.SysMenuModel
}

func NewDeleteMenuLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteMenuLogic {
	return &DeleteMenuLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		menuModel: model.NewSysMenuModel(svcCtx.Orm),
	}
}

func (l *DeleteMenuLogic) DeleteMenu(req *types.IdRequest) (resp *types.CommonResponse, err error) {
	// todo: add your logic here and delete this line
	err = auth.HasPermission(l.menuModel,l.ctx,"system:menu:remove")
	if err != nil {
		return nil,errorx.Unauthorized
	}
	roleIds,err := auth.GetRoleIds(l.ctx)
	if err != nil {
		return nil,errorx.AuthNoFound
	}
	if isAdmin,_ := auth.IsAdmin(l.ctx); !isAdmin {
		err = l.menuModel.ExistByMIdRIds(l.ctx,nil,req.Id,roleIds)
		if err != nil {
			return nil,errorx.Unauthorized
		}
	}

	menuIds := make([]*int64,0)
	menuList := make([]*model.SysMenu,0)
	menu,err := l.menuModel.FindOne(l.ctx,req.Id)
	if err != nil {
		return nil,errorx.SqlSearchError
	}
	menuList = append(menuList, menu)
	menuIds = append(menuIds, &menu.MenuId)
	if menu.MenuType != common.BUTTON_TYPE {
		err = TreeSelect(l.ctx,l.menuModel,menuList,&menuIds)
		if err != nil {
			return nil,errorx.SqlSearchError
		}
	}
	err = l.menuModel.DeleteByIds(l.ctx,nil,menuIds)
	return &types.CommonResponse{
		Status: 200,
		Msg: "删除成功",
	},err
}

//树状查询
func TreeSelect(ctx context.Context,menuModel model.SysMenuModel,parents []*model.SysMenu,keeped *[]*int64)error {
	selectIds := make([]*int64,0)
	for _,val := range parents {
		if val.MenuType != common.BUTTON_TYPE {
			selectIds = append(selectIds, &val.MenuId)
		}
	}
	menus,err := menuModel.GetListByParentIds(ctx,nil,selectIds)
	if err != nil {
		if err == sqlx.ErrNotFound {
			return nil
		}else{
			return err
		}
	}
	for _,val := range menus {
		*keeped = append(*keeped, &val.MenuId)
	}
	if len(menus) > 0 {
		TreeSelect(ctx,menuModel,menus,keeped)
	}
	return nil

}
